﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using STLGROUP.Layers.Presentations.FormBase;
using STLGROUP.Layers.Common;
using STLGROUP.Layers.BLL;
using STLGROUP.Layers.DataAccessLayers;
using STLGROUP.Controls;

namespace QuanLyBanHang
{
    /// <summary>
    /// MF008 - Dat hang tu nha cung cap
    /// </summary>
    /// <author>viet sang</author>
    /// <date>22/04/2012</date>
    public partial class MF008 : frmManager
    {
        #region Variables

        DatHangBLL _business;
        View_SanPham _current;
        View_DatHangNhaCungCap _currentDat;
        List<View_DatHangNhaCungCap> _lstDatHang;
        View_DatHangNhaCungCap _sanPham;
        int? _idNhaCungCap = null;

        STLBindingSource _bindSource2;

        #endregion

        #region Contructors

        public MF008()
        {
            InitializeComponent();
            InitializeForm();
        }

        #endregion

        #region Protected methods

        protected override int UpdateData()
        {
            if (!CheckData())
            {
                return -1;
            }

            DT_DonDatHang donHang = new DT_DonDatHang()
            {
                //MaDonDatHang = "()()()()()", //cap nhat sau
                IDKhachHang = _idNhaCungCap,
                IDLoaiGiaoDich = (int)StructsEnums.EnumLoaiGiaoDich.DatHangNhaCungCap,
                IDNhanVienXacNhan = UICommon.CurrentUserInfo.IDNhanVien,
                TongTien = decimal.Parse(txtTongTien.Text),
                DaThanhToan = decimal.Parse(txtDuaTruoc.Text),
                NgayThanhToan = dtiHanThanhToan.Value,
                IDTrangThaiDonHang = (int?)StructsEnums.EnumTrangThaiDonHang.DangDatHang,
                NgayTao = DateTime.Now
            };

            _business.Context.DT_DonDatHang.AddObject(donHang);
            _business.Context.SaveChanges();

            //getIndentity
            int idDonHang = _business.Context.DT_DonDatHang.Max(s => s.IDDonDatHang);

            //update MaDonHang
            DT_DonDatHang dh = _business.Context.DT_DonDatHang.Where(s => s.IDDonDatHang == idDonHang).FirstOrDefault();
            if(dh!=null)
            {
                dh.MaDonDatHang = GetNewMaDonHang(idDonHang);
            }

            //update chi tiet don hang
            foreach (View_DatHangNhaCungCap item in _lstDatHang)
            {
                DT_ChiTietDonHang ctDonhang = new DT_ChiTietDonHang() { 
                    IDDonDatHang = idDonHang,
                    IDSanPhan = item.IDSanPham,
                    SoLuong = item.SoLuongDat,
                    GiaBan = item.GiaNhap,
                    NguoiTao = UICommon.CurrentUserInfo.IDNhanVien,
                    NgayTao = DateTime.Now
                };

                _business.Context.DT_ChiTietDonHang.AddObject(ctDonhang);           
            }

            int kq = _business.Context.SaveChanges();

            if (kq > 0)
            {
                ClearAll();

                RF004 frmReport = new RF004() { IDDonHang = idDonHang };
                frmReport.ShowDialog();

                return kq;
            }

            return -1;            
        }

        protected override void Filter()
        {
            int? idNCC = null;
            int? idLSP = null;
            if(cboNhaCungCap.SelectedValue!=null)
            {
                idNCC = Convert.ToInt32(cboNhaCungCap.SelectedValue.ToString());
            }
            if (cboLoaiSanPham.SelectedValue != null)
            {
                idLSP = Convert.ToInt32(cboLoaiSanPham.SelectedValue.ToString());
            }   

            this._bindingSource.DataSource = _business.GetSanPhamByContidions(idNCC, idLSP, chbxSoLuongCanhBao.Checked);
            this.grid1.DataSource = this._bindingSource;
        }

        protected override void CancelAddinng()
        {
            ClearAll();
        }

        #endregion

        #region Private Methods

        private void InitializeForm()
        {
            _business = new DatHangBLL();
            _lstDatHang = new List<View_DatHangNhaCungCap>();
            _bindSource2 = new STLBindingSource();
            //_sanPham = new DT_SanPham();


            pnlChiTiet.Enabled = true;
            tsbLuu.Enabled = true;

            cboLoaiSanPham.SelectedValueChanged += new EventHandler(cbo_SelectedValueChanged);
            cboNhaCungCap.SelectedValueChanged += new EventHandler(cbo_SelectedValueChanged);

            cboLoaiSanPham.DataSource = Cache.Context.DM_LoaiSanPham;
            cboLoaiSanPham.DisplayMember = "TenLoaiSanPham";
            cboLoaiSanPham.ValueMember = "IDLoaiSanPham";

            cboNhaCungCap.DataSource = Cache.Context.DT_NhaCungCap;
            cboNhaCungCap.DisplayMember = "TenNhaCungCap";
            cboNhaCungCap.ValueMember = "IDNhaCungCap";

            this._bindingSource.CurrentChanged += new EventHandler(_bindingSource_CurrentChanged);
            this.Load += new EventHandler(MF008_Load);

            tsbCancel.Enabled = true;
            tsbCancel.Click += new EventHandler(tsbCancel_Click);
            txtTongTien.TextChanged += new EventHandler(txtTongTienDuaTruoc_Leave);

            btnHuy.Click += new EventHandler(btnHuy_Click);
            _bindSource2.CurrentChanged += new EventHandler(_bindSource2_CurrentChanged);


            dtiHanThanhToan.Value = DateTime.Today.AddDays(7);
        }

        private void LoadStatus()
        {
            txtTongTien.Text = _lstDatHang.Sum(s => s.ThanhTienTMP).ToString("N0");
            txtNhaCungCap.Text = Cache.Context.DT_NhaCungCap.Where(s => s.IDNhaCungCap == _idNhaCungCap).Select(s => s.TenNhaCungCap).FirstOrDefault() ?? string.Empty;
        }

        private void ClearAll()
        {
            _lstDatHang = new List<View_DatHangNhaCungCap>();
            _current = null;
            _idNhaCungCap = null;
            _bindSource2.DataSource = _lstDatHang;


            _bindSource2.DataSource = null;
            grid2.DataSource = null;
            grid2.DataSource = _lstDatHang;

            txtTongTien.Text = string.Empty;
            txtDuaTruoc.Text = string.Empty;
            txtConLai.Text = string.Empty;

            pnlChiTiet.Enabled = true;
        }

        public string GetNewMaDonHang(int pIDDonHang)
        {
            return "DH" + pIDDonHang.ToString().PadLeft(3, '0');
        }

        public bool CheckData()
        {
            if (_idNhaCungCap == null)
            {
                UICommon.ShowMessegeInfo(Const.MSG_CHUA_CHON_NHACUNGCAP);
                return false;
            }
            if (string.IsNullOrEmpty(txtTongTien.Text))
            {
                UICommon.ShowMessegeInfo(Const.MSG_TONGTIEN_PHAILONHON_KHONG);                
                return false;
            }
            
            if (string.IsNullOrEmpty(txtDuaTruoc.Text))
            {
                UICommon.ShowMessegeInfo(Const.MSG_SOTIEN_TAM_UNG_NOT_NULL);
                txtDuaTruoc.Focus();
                return false;
            }
            if (double.Parse(txtDuaTruoc.Text) > double.Parse(txtTongTien.Text))
            {
                UICommon.ShowMessegeInfo(Const.MSG_SOTIEN_TAMUNG_PHAI_NHOHON_HOAC_BANG_TONGTIEN);
                txtDuaTruoc.Focus();
                return false;
            }
            if (dtiHanThanhToan.Value <= DateTime.Today) 
            {
                UICommon.ShowMessegeInfo(Const.MSG_NGAYTHANH_TOAN_PHAI_SAUNGAYHOMNAY);
                dtiHanThanhToan.Focus();
                return false;
            }

            return true;
        }

        #endregion

        #region Events

        private void cbo_SelectedValueChanged(object sender, EventArgs e)
        {
            
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            if (_current == null)
            {
                UICommon.ShowMessegeInfo(Const.MSG_CHUA_CHON_SAN_PHAM);
                return;
            }
            else
            {
                _sanPham = _lstDatHang.Where(s => s.IDSanPham == _current.IDSanPham).FirstOrDefault();
                if (_sanPham != null)
                {
                    _sanPham.SoLuongDat += txtSoLuongDat.Value;
                }
                else
                {
                    _sanPham = new View_DatHangNhaCungCap()
                    {
                        IDSanPham = _current.IDSanPham,
                        MaSanPham = _current.MaSanPham,
                        TenSanPham = _current.TenSanPham,
                        GiaNhap = _current.GiaNhap??0,
                        DonViTienTe = _current.DonViTienTe,
                        IDDonViTinh = _current.IDDonViTinh,
                        TenDonViTinh = _current.TenDonViTinh,
                        SoLuongDat = txtSoLuongDat.Value
                    };
                    _lstDatHang.Add(_sanPham);
                }
            }
            _bindSource2.DataSource = _lstDatHang;
            grid2.DataSource = null;
            grid2.DataSource = _bindSource2;

            _idNhaCungCap = _idNhaCungCap.HasValue ? _idNhaCungCap : _current.IDNhaCungCap;            

            LoadStatus();

            pnlChiTiet.Enabled = false;
        }

        private void _bindingSource_CurrentChanged(object sender, EventArgs e)
        {
            if (_bindingSource != null && _bindingSource.Current != null)
            {
                _current = _bindingSource.Current as View_SanPham;
                txtSoLuongDat.Value = 1;
            }
            else
            {
                _current = null;
            }
        }

        private void MF008_Load(object sender, EventArgs e)
        {
            this._bindingSource.DataSource = _business.GetSanPhamByContidions(null,null);
            this.grid1.DataSource = this._bindingSource;

            txtNhanVien.Text = UICommon.CurrentUserInfo.MaNhanVien + "-" + UICommon.CurrentUserInfo.HoTenNhanVien;

        }

        private void tsbCancel_Click(object sender, EventArgs e)
        {
            ClearAll();

        }

        private void txtTongTienDuaTruoc_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtDuaTruoc.Text)&& !string.IsNullOrEmpty(txtTongTien.Text))
            {
                txtDuaTruoc.Text = double.Parse(txtDuaTruoc.Text).ToString(Const.DINH_DANG_HIEN_THI_TIEN);
                txtConLai.Text = string.Empty;
                txtConLai.Text = (double.Parse(txtTongTien.Text) - double.Parse(txtDuaTruoc.Text)).ToString(Const.DINH_DANG_HIEN_THI_TIEN);
            }
        }

        private void txtConLai_TextChanged(object sender, EventArgs e)
        {
            STLTextBox txt = sender as STLTextBox;
            if (!string.IsNullOrEmpty(txt.Text))
            {
                lblTongTienPhaiText.Text = UICommon.NumberToString(double.Parse(txt.Text));
            }
            else
            {
                lblTongTienPhaiText.Text = string.Empty;
            }
        }

        private void btnHuy_Click(object sender, EventArgs e)
        {
            if (_currentDat != null)
            {
                _currentDat.SoLuongDat -= txtSoLuongDat.Value;
                if (_currentDat.SoLuongDat <= 0)
                {
                    _bindSource2.Remove(_currentDat);
                }

                _lstDatHang = _bindSource2.DataSource as List<View_DatHangNhaCungCap>;

                grid2.DataSource = null;
                grid2.DataSource = _bindSource2;

                LoadStatus();

            }
        }

        private void _bindSource2_CurrentChanged(object sender, EventArgs e)
        {
            if (_bindSource2.Current != null)
            {
                _currentDat = _bindSource2.Current as View_DatHangNhaCungCap;
            }
            else
            {
                _currentDat = null;
            }
        }


        #endregion

    }
}
